<template>
  <el-container class="layout-container">
    <el-aside width="220px" class="aside-container">
      <div class="logo-container">
        <img src="@/assets/logo.svg" alt="Logo" class="logo" />
        <h1 class="title">汽车租赁系统</h1>
      </div>
      <el-menu
        router
        :default-active="$route.path"
        class="el-menu-vertical"
        :collapse="isCollapse"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
        <el-menu-item index="/data-dashboard">
          <el-icon><PieChart /></el-icon>
          <template #title>数据统计</template>
        </el-menu-item>
        <el-menu-item index="/reservation">
          <el-icon><Calendar /></el-icon>
          <template #title>预约申请</template>
        </el-menu-item>
        <el-menu-item index="/car-status">
          <el-icon><Van /></el-icon>
          <template #title>车辆状态</template>
        </el-menu-item>
        <el-menu-item index="/maintenance">
          <el-icon><Tools /></el-icon>
          <template #title>维修管理</template>
        </el-menu-item>
        <el-menu-item index="/return">
          <el-icon><Back /></el-icon>
          <template #title>还车处理</template>
        </el-menu-item>
        <el-sub-menu index="management">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>基础管理</span>
          </template>
          <el-menu-item index="/car-management">
            <el-icon><Van /></el-icon>
            <template #title>车辆管理</template>
          </el-menu-item>
          <el-menu-item index="/customer-management">
            <el-icon><User /></el-icon>
            <template #title>客户管理</template>
          </el-menu-item>
          <el-menu-item index="/rental-management">
            <el-icon><Document /></el-icon>
            <template #title>租赁管理</template>
          </el-menu-item>
          <el-menu-item index="/employee-management">
            <el-icon><UserFilled /></el-icon>
            <template #title>员工管理</template>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    <el-container class="main-container">
      <el-header class="header-container">
        <div class="header-left">
          <el-icon class="collapse-btn" @click="toggleCollapse">
            <Fold v-if="!isCollapse" />
            <Expand v-else />
          </el-icon>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="(item, idx) in currentRoute" :key="idx">{{ item }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-dropdown>
            <span class="user-dropdown">
              <el-avatar :size="32" :src="avatarUrl" />
              <span class="username">管理员</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-icon><User /></el-icon>
                  <span class="dropdown-item-text">账号：{{ username }}</span>
                </el-dropdown-item>
                <el-dropdown-item @click="$router.push('/profile')">
                  <el-icon><User /></el-icon>
                  个人信息
                </el-dropdown-item>
                <el-dropdown-item @click="$router.push('/change-password')">
                  <el-icon><Lock /></el-icon>
                  修改密码
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-main>
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  Calendar, 
  Van, 
  Tools, 
  Back, 
  Setting, 
  User, 
  Document,
  Fold,
  Expand,
  Lock,
  SwitchButton,
  UserFilled,
  PieChart
} from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { logout } from '@/api/auth'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const isCollapse = ref(false)

const avatarUrl = computed(() => {
  if (!userStore.userInfo.image) return '/src/assets/avatar.svg'
  const timestamp = new Date().getTime()
  return `${userStore.userInfo.image}?t=${timestamp}`
})

const username = computed(() => userStore.userInfo.username || '')

const fetchUserInfo = async () => {
  if (route.path === '/login') return

  try {
    const token = localStorage.getItem('Token')
    if (!token) return

    const response = await fetch('http://localhost:8080/user', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      router.push('/login')
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    if (result.code === 200) {
      userStore.updateUserInfo({
        image: result.data.image,
        username: result.data.username,
        name: result.data.name,
        phone: result.data.phone,
        email: result.data.email,
        department: result.data.department,
        position: result.data.position
      })
      
      localStorage.setItem('user', JSON.stringify(result.data))
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    if (route.path !== '/login') {
      ElMessage.error('获取用户信息失败：' + error.message)
    }
  }
}

onMounted(() => {
  fetchUserInfo()
})

watch(() => route.path, (newPath) => {
  if (newPath !== '/login') {
    fetchUserInfo()
  }
})

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

const currentRoute = computed(() => {
  const routeMap = {
    '/data-dashboard': ['首页', '数据统计'],
    '/reservation': ['首页', '预约申请'],
    '/car-status': ['首页', '车辆状态'],
    '/maintenance': ['首页', '维修管理'],
    '/return': ['首页', '还车处理'],
    '/car-management': ['基础管理', '车辆管理'],
    '/customer-management': ['基础管理', '客户管理'],
    '/rental-management': ['基础管理', '租赁管理'],
    '/employee-management': ['基础管理', '员工管理']
  }
  return routeMap[route.path] || ['首页']
})

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await logout()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error)
      ElMessage.error('退出登录失败')
    }
  }
}
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.aside-container {
  background-color: #304156;
  transition: width 0.3s;
  overflow: hidden;
}

.logo-container {
  height: 60px;
  padding: 10px;
  display: flex;
  align-items: center;
  background-color: #2b3649;
}

.logo {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.title {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  white-space: nowrap;
}

.el-menu {
  border-right: none;
}

.main-container {
  flex: 1;
}

.header-container {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.collapse-btn {
  font-size: 20px;
  margin-right: 20px;
  cursor: pointer;
  color: #606266;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 8px;
  color: #606266;
}

.dropdown-item-text {
  margin-left: 8px;
}

.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}
</style>